package com.dna.okangjang.main.dao.rest;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.dna.okangjang.main.dao.NaverApiDao;
import com.dna.okangjang.main.model.NImage;

@Repository("naverApiDao")
public class NaverApiDaoRest implements NaverApiDao {
	private static final Log logger = LogFactory.getLog(NaverApiDaoRest.class);
	
	private static final String SEARCH_API = "http://openapi.naver.com/search";
	private static final String API_KEY = "0801867437558c65bb4905bcf3b0db3f";
	
	@Resource
	private RestTemplate restTemplate;
	
	@Override
	public List<NImage> getSearchImage(String query, int page, int row) {
		String prefix = SEARCH_API;
		String enc_query = null;
		try {
			enc_query = URLEncoder.encode(query, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			logger.error(">>> encoding error");
		}
		
		int start = (page-1) * row + 1;
		String api_url = new StringBuffer(prefix).append("?").append("target=image")
				.append("&key=").append(API_KEY).append("&query=").append(enc_query)
				.append("&start=").append(start).append("&display=").append(row)
				.append("&filter=small").toString();
		logger.debug(">>> api_url : " + api_url);
		
		String str = null;
		try{
			str = restTemplate.getForObject(new URI(api_url), String.class);
		} catch(RestClientException e){
			logger.error(">>> search error");
		} catch(URISyntaxException e){
			logger.error(">>> search error");
		}
		
		List<NImage> list = new ArrayList<NImage>();
		if(str != null){
			try{
				XMLSerializer xmlSerializer = new XMLSerializer();
				JSONObject obj = (JSONObject) xmlSerializer.read(str);
				obj = obj.getJSONObject("channel");
				int total = obj.getInt("total");
				if(total == 0) return list;
				
				if(total == 1){
					JSONObject ob = obj.getJSONObject("item");
					NImage img = (NImage) JSONObject.toBean(ob, NImage.class);
					list.add(img);
				} else{
					JSONArray arr = obj.getJSONArray("item");
					for(int i=0; i<arr.size(); i++){
						NImage img = (NImage) JSONObject.toBean(arr.getJSONObject(i), NImage.class);
						list.add(img);
					}
				}
				
			} catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return list;
	}

}
